using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.Domain.SalesManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement.Billing;

namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement.Billing
{
    /// <summary>
    /// 获取开票明细列表查询处理器
    /// </summary>
    public class GetBillingDetailListHandler : IRequestHandler<GetBillingDetailListCommand, APIResult<GetBillingDetailListDto>>
    {
        private readonly RBACDbContext _dbContext;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库上下文</param>
        public GetBillingDetailListHandler(RBACDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 处理获取开票明细列表查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>开票明细列表结果</returns>
        public async Task<APIResult<GetBillingDetailListDto>> Handle(GetBillingDetailListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 构建基础查询 - 直接从物料明细表查询
                var query = _dbContext.Set<BillingMaterials>()
                    .Where(bm => !bm.IsDeleted)
                    .Join(_dbContext.Set<BillingAccounting>()
                            .Where(b => !b.IsDeleted),
                        bm => bm.BillingAccountingId,
                        b => b.Id,
                        (bm, b) => new { Material = bm, Bill = b })
                    .AsQueryable();

                // 应用搜索条件
                if (!string.IsNullOrWhiteSpace(request.BillNo))
                {
                    query = query.Where(x => x.Bill.BillNumber != null && x.Bill.BillNumber.Contains(request.BillNo));
                }

                if (!string.IsNullOrWhiteSpace(request.CustomerName))
                {
                    query = query.Where(x => x.Bill.CustomerName != null && x.Bill.CustomerName.Contains(request.CustomerName));
                }

                if (!string.IsNullOrWhiteSpace(request.InvoiceName))
                {
                    query = query.Where(x => x.Material.InvoiceName != null && x.Material.InvoiceName.Contains(request.InvoiceName));
                }

                if (request.StartDate.HasValue)
                {
                    query = query.Where(x => x.Bill.BillDate >= request.StartDate.Value);
                }

                if (request.EndDate.HasValue)
                {
                    query = query.Where(x => x.Bill.BillDate <= request.EndDate.Value.Date.AddDays(1).AddTicks(-1));
                }

                // 获取总记录数
                var totalCount = await query.CountAsync(cancellationToken);

                // 分页查询
                var billingDetails = await query
                    .OrderByDescending(x => x.Bill.CreateTime)
                    .ThenBy(x => x.Material.OrderNumber)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .Select(x => new BillingDetailDto
                    {
                        Id = x.Material.Id,
                        BillNumber = x.Bill.BillNumber,
                        CustomerName = x.Bill.CustomerName ?? "",
                        BillDate = x.Bill.BillDate,
                        OrderNumber = x.Material.OrderNumber,
                        MaterialCode = x.Material.MaterialCode,
                        MaterialName = x.Material.MaterialName,
                        Specification = "", // 假设规格型号为空，实际应根据业务调整
                        Unit = x.Material.Unit,
                        Quantity = x.Material.Quantity,
                        UnitPrice = x.Material.UnitPrice,
                        Amount = x.Material.Amount,
                        InvoiceName = x.Material.InvoiceName,
                        Remarks = x.Material.Remarks,
                        BillStatus = x.Bill.BillStatus
                    })
                    .ToListAsync(cancellationToken);

                var result = new GetBillingDetailListDto
                {
                    PageDatas = billingDetails,
                    TotalCount = totalCount
                };

                return new APIResult<GetBillingDetailListDto>
                {
                    Code = APIEnums.Success,
                    Msg = "获取开票明细列表成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new APIResult<GetBillingDetailListDto>
                {
                    Code = APIEnums.Fail,
                    Msg = "获取开票明细列表失败：" + ex.Message,
                    Data = new GetBillingDetailListDto()
                };
            }
        }
    }
}